package simplecoder.wizards;

import java.util.List;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import com.sun.istack.internal.FinalArrayList;

import simplecoder.domain.Field;
import simplecoder.domain.Module;

@SuppressWarnings( { "restriction" })
public class CodeGenerationWizardPage extends WizardPage
{
	private Text entityPackageText;//dao包名
	private Text daoPackageText;//dao包名
	private Text servicPackageText; //service包名
	private Text actionPackageText;//action包名
	
	private Text moduleTitleText;//

	private ISelection selection;

	protected CodeGenerationWizardPage(ISelection selection) {
		super("SimpleCoder");
		setTitle("代码生成");
		setDescription("相应的包名");
		this.selection = selection;
	}

	//@Override
	public void createControl(final Composite parent) {
		//创建一个新的Composite
		Composite container = new Composite(parent, SWT.NULL);
		//设置网格布局
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 2;
		layout.verticalSpacing = 9;//垂直间距
		//---------------------------------------------------------------
		Label label = new Label(container, SWT.NULL);
		label.setText("生成的对象是:");
		entityPackageText = new Text(container, SWT.READ_ONLY | SWT.BORDER | SWT.SINGLE);
		entityPackageText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		//---------------------------------------------------------------
		label = new Label(container, SWT.NULL);
		label.setText("dao包路径:");
		daoPackageText = new Text(container, SWT.READ_ONLY | SWT.BORDER | SWT.SINGLE);
		daoPackageText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		//---------------------------------------------------------------
		label = new Label(container, SWT.NULL);
		label.setText("service包路径:");
		servicPackageText = new Text(container, SWT.READ_ONLY | SWT.BORDER | SWT.SINGLE);
		servicPackageText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		//---------------------------------------------------------------
		label = new Label(container, SWT.NULL);
		label.setText("action包路径:");
		actionPackageText = new Text(container, SWT.READ_ONLY | SWT.BORDER | SWT.SINGLE);
		actionPackageText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		//---------------------------------------------------------------
		
		new Label(container, SWT.LEFT).setText("输入模块名称：");
	    moduleTitleText = new Text(container, SWT.BORDER);
	    moduleTitleText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
	    moduleTitleText.addVerifyListener(new VerifyListener() {
	        //当文本框字符改变时
	        public void verifyText(VerifyEvent e) {
	        	//如果此时符合email的格式
	        	if (moduleTitleText.getText().length() > 0) {
	        		//设置错误消息为null
	        		setErrorMessage(null);
	        		//设置页面完成,“下一步”按钮置可用
	        		setPageComplete(true);
	        	} 
	        }
	    });
	    
	    new Label(container, SWT.LEFT).setText("");
		Button editFieldButton = new Button(container, SWT.PUSH);
		editFieldButton.setText("选择编辑表单中的字段");
		// 添加确定按钮事件
		editFieldButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				CodeGenerationEdit hwjf = new CodeGenerationEdit(parent.getShell());
				hwjf.setBlockOnOpen(true);
				hwjf.open();
			}
		});
		
		new Label(container, SWT.LEFT).setText("");
		Button gridFieldButton = new Button(container, SWT.PUSH);
		gridFieldButton.setText("选择列表中的字段");
		// 添加确定按钮事件
		gridFieldButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				CodeGenerationGrid hwjf = new CodeGenerationGrid(parent.getShell());
				hwjf.setBlockOnOpen(true);
				hwjf.open();
			}
		});
	    
	    
	  //设置焦点
		parent.setFocus();
		//初始化界面默认
		initialize();
		
	    
//	    new Label(container, SWT.LEFT).setText("选择要生成表单的字段：");
//	    Button b1 = new Button(container,SWT.CHECK);
//	    b1.setText("id");
//	    new Label(container, SWT.LEFT).setText("");
//	    Button b2 = new Button(container,SWT.CHECK);
//	    b2.setText("name");
	    
	    
		

		dialogChanged();

		setControl(container);
	}

	/**
	 * 初始化界面默认值
	 */
	private void initialize(){
		try {
			System.out.println("-----------------------code---------------------------------");
			if (selection != null && selection.isEmpty() == false && selection instanceof IStructuredSelection) {
				IStructuredSelection ssel = (IStructuredSelection) selection;

				Object obj = ssel.getFirstElement();
				
				if (obj instanceof ICompilationUnit) {
					ICompilationUnit icu = (ICompilationUnit) obj;
					
					String elementName = icu.getElementName();
					String pojoName = elementName.substring(0, elementName.indexOf("."));
					String packName = icu.getPackageDeclarations()[0].getElementName();
					
					ASTParser parser = ASTParser.newParser(AST.JLS3);
					parser.setKind(ASTParser.K_COMPILATION_UNIT);
					parser.setSource(icu);//设置资源
					parser.setResolveBindings(true);// 后面需要绑定
					CompilationUnit cu = (CompilationUnit) parser.createAST(null);
					
					List types = cu.types();
					TypeDeclaration typeDec = (TypeDeclaration) types.get(0);
					FieldDeclaration[] fieldDecs = typeDec.getFields();
					
					//System.out.println("source:"+icu.getSource());
					String fullpath = icu.getResource().getFullPath().toString();
					String sourcePath =fullpath.substring(0, fullpath.indexOf("/"+packName.replaceAll("\\.", "/")));
					System.out.println("sourcePath:"+sourcePath);
					
					//构建模块对象
					Module module = Module.create(sourcePath, pojoName, packName);
					for (FieldDeclaration fieldDec : fieldDecs){
						
						//字段类型
						String type = fieldDec.getType().toString();
						String name = null;
						for (Object fragment : fieldDec.fragments()) {
							VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment;
							//字段名称
							name = frag.getName().toString();
						}
						module.getPojo().addField(name, type);
					}
					
					entityPackageText.setText(module.getPojo().getClassName());
					daoPackageText.setText(module.getDao().getClassName());
					servicPackageText.setText(module.getService().getClassName());
					actionPackageText.setText(module.getAction().getClassName());
					
					//以下是测试代码，没用到，但暂时保留以备忘
					
//					List types = cu.types();
//					TypeDeclaration typeDec = (TypeDeclaration)types.get(0) ;
//					MethodDeclaration[] mds = typeDec.getMethods();
//					
//					for (MethodDeclaration md : mds) {
//						System.out.println("methodName:"+md.getName().toString());
//						
//					}
					
//					IType type = icu.getTypes()[0];
//					
//					
//					IMethod[] methos = type.getMethods();
//					System.out.println("Imethod start");
//					for (IMethod method : methos) {
//						System.out.println(method.getElementName());;
//						System.out.println(method.getSource());
//					}
					
					
					
				   
					//生成一个类的代码
//					try {
//						String javaCode = "package com.aptech.plugin;public class HelloWorld{public static void main(String[] args){System.out.println(\"中华人民共和国\");}}";
//						IPackageFragmentRoot packageFragmentRoot = javaProject
//						.findPackageFragmentRoot(new Path("/xyz/src"));
//					    IPackageFragment packageFragment = packageFragmentRoot
//						.getPackageFragment("com.aptech.plugin");
//						packageFragment.createCompilationUnit("HelloWorld.java", javaCode,
//					   true, new NullProgressMonitor());
//				    } catch (JavaModelException e) {
//					   // TODO Auto-generated catch block
//					   e.printStackTrace();
//					} catch (Exception e) {
//					   // TODO Auto-generated catch block
//					   e.printStackTrace();
//					}
					
//					for (FieldDeclaration fd : fieldDecs) {
////						for (Object fragment : fd.fragments())
////						{
////							VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment;
////							frag.
////							//字段名称
////							System.out.println("fieldName:"+frag.getName().toString());
////						}
//					}
					
					
					
//					PackageNameInfo packageNameInfo = new PackageNameInfo(packageFragment);
//					entityPackageText.setText(packageFragment.getElementName());
//					daoPackageText.setText(packageFragment.getElementName());
//					servicPackageText.setText(packageFragment.getElementName());
//					actionPackageText.setText(packageFragment.getElementName());
				}
			}
		} catch (Exception e) {
			System.out.println("出错 了");
			e.printStackTrace();
		}
		
	}

	/**
	 * 验证
	 */
	private void dialogChanged() {
		if (entityPackageText.getText().length() == 0) {
			updateStatus("请选择一个基于注解的Hibernte实体类");
			return;
		}
		if(moduleTitleText.getText().length() == 0){
			System.out.println("text:"+moduleTitleText.getText()+" "+moduleTitleText.getMessage());
			updateStatus("请输入模块名称");
			return;
		}
//		if (!entityPackageName.endsWith(".entity"))
//		{
//			updateStatus("你�?�择的实体包名必须为entity，如“com.google.blog.entity”中的entity");
//			return;
//		}
//		if (StringUtils.countMatches(entityPackageName, ".") < 3)
//		{
//			updateStatus("实体包必须在4层以上，注意实体包名的上�?层包名为模块名，如�?�org.slave4j.blog.entity”中“blog”为博客模块");
//			return;
//		}
		updateStatus(null);
	}
	
	public Text getModuleTitleText() {
		return moduleTitleText;
	}

	/**
	 * 改变向导页状态
	 * @param message
	 */
	private void updateStatus(String message) {
		setErrorMessage(message);
		setPageComplete(message == null);//完成按钮是否有效
	}
}
